package com.kakarote.oa.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.kakarote.common.field.entity.ModelFieldExtend;
import com.kakarote.common.field.utils.FieldUtil;
import com.kakarote.core.common.Const;
import com.kakarote.core.common.enums.FieldEnum;
import com.kakarote.core.servlet.BaseServiceImpl;
import com.kakarote.oa.entity.PO.OaExamineFieldExtend;
import com.kakarote.oa.mapper.OaExamineFieldExtendMapper;
import com.kakarote.oa.service.IOaExamineFieldExtendService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * <p>
 * 自定义字段表 服务实现类
 * </p>
 *
 * @author JiaS
 * @since 2021-03-04
 */
@Service
public class OaExamineFieldExtendServiceImpl extends BaseServiceImpl<OaExamineFieldExtendMapper, OaExamineFieldExtend> implements IOaExamineFieldExtendService {

    @Override
    public List<OaExamineFieldExtend> queryOaExamineFieldExtend(Long parentFieldId) {
        List<OaExamineFieldExtend> fieldExtends = lambdaQuery().eq(OaExamineFieldExtend::getParentFieldId, parentFieldId).list();
        FieldUtil.recordToFormType(fieldExtends);
        return fieldExtends;
    }

    @Override
    public boolean saveOrUpdateOaExamineFieldExtend(List<? extends ModelFieldExtend> oaExamineFieldExtendList, Long parentFieldId, boolean isUpdate) {
        if (parentFieldId == null) {
            return false;
        }
        if (isUpdate) {
            this.deleteOaExamineFieldExtend(parentFieldId);
        }
        List<OaExamineFieldExtend> oaFieldExtends = new ArrayList<>();
        for (ModelFieldExtend fieldExtend : oaExamineFieldExtendList) {
            if (ObjectUtil.isEmpty(fieldExtend.getDefaultValue())) {
                fieldExtend.setDefaultValue("");
            } else {
                boolean isNeedHandle = FieldUtil.equalsByType(fieldExtend.getType(), FieldEnum.AREA, FieldEnum.AREA_POSITION, FieldEnum.CURRENT_POSITION);
                if (isNeedHandle) {
                    fieldExtend.setDefaultValue(JSON.toJSONString(fieldExtend.getDefaultValue()));
                }
                if (fieldExtend.getDefaultValue() instanceof Collection) {
                    fieldExtend.setDefaultValue(StrUtil.join(Const.SEPARATOR, fieldExtend.getDefaultValue()));
                }
            }
            fieldExtend.setId(null);
            fieldExtend.setParentFieldId(parentFieldId);
            OaExamineFieldExtend oaExamineFieldExtend = BeanUtil.copyProperties(fieldExtend, OaExamineFieldExtend.class);
            oaFieldExtends.add(oaExamineFieldExtend);
        }
        saveBatch(oaFieldExtends);
        return true;
    }

    @Override
    public boolean deleteOaExamineFieldExtend(Long parentFieldId) {
        return lambdaUpdate().eq(OaExamineFieldExtend::getParentFieldId, parentFieldId).remove();
    }
}
